package core

import (
	"gitee.com/feimos/dm/utils"
	"sort"
	"strconv"
	"strings"
	"time"
)

type FindItem struct {
	Name string
	Size int64
	Time time.Time
}

type FindList []*FindItem

type TimeSortList FindList

type SizeSortList FindList

func (t TimeSortList) Len() int {
	return len(t)
}

func (t TimeSortList) Less(i, j int) bool {
	timeI := t[i].Time
	timeJ := t[j].Time

	timeI.After(timeJ)
	return timeI.After(timeJ)
}

func (t TimeSortList) Swap(i, j int) {
	t[i], t[j] = t[j], t[i]
}

func (s SizeSortList) Len() int {
	return len(s)
}

func (s SizeSortList) Less(i, j int) bool {

	return s[i].Size-s[j].Size > 0
}

func (s SizeSortList) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func FindDocument(yamlContent *YamlContent, name string, ignoreCase bool) FindList {

	var res FindList

	for _, infos := range yamlContent.Nodes {

		for _, info := range infos {

			if ignoreCase {
				tempB := strings.ToLower(name)
				tempA := strings.ToLower(info.Name)
				if strings.Contains(tempA, tempB) {
					res = append(res, &FindItem{
						Name: info.Name,
						Size: info.Size,
						Time: info.Time,
					})
				}

			} else {
				if strings.Contains(info.Name, name) {
					res = append(res, &FindItem{
						Name: info.Name,
						Size: info.Size,
						Time: info.Time,
					})
				}
			}
		}
	}
	return res
}

func FilterFindList(findResult FindList, count int, timeSort int, sizeSort int) [][]string {

	var res [][]string

	if timeSort < 0 {
		sort.Sort(TimeSortList(findResult))
	} else if timeSort > 0 {
		sort.Sort(sort.Reverse(TimeSortList(findResult)))
	}

	if sizeSort < 0 {
		sort.Sort(SizeSortList(findResult))
	} else if sizeSort > 0 {
		sort.Sort(sort.Reverse(SizeSortList(findResult)))
	}

	for index, findItem := range findResult {

		indexString := strconv.Itoa(index + 1)
		sizeString := utils.FormatFileSize(findItem.Size)
		timeString := utils.SubString(findItem.Time.String(), 19)
		item := []string{indexString, findItem.Name, sizeString, timeString}
		res = append(res, item)

		if index >= count-1 {
			break
		}
	}

	return res

}
